import config
import json
from random_word import RandomWords as rand
from bs4 import BeautifulSoup
import requests as req
from utils import *

def register():
	return RandomWords()

class RandomWords:
	def __init__(self):
		self.type = 'passive'

	def searchWord(self, word):
		result = []
		try:
			r = req.get(f'https://dict.youdao.com/w/{word}')
			r.encoding = 'utf-8'
			soup = BeautifulSoup(r.text, 'html.parser')
			trans_container = soup.find(class_='trans-container')
			for li in trans_container.find_all('li'):
				result.append(li.text.strip())
		except Exception:
			return ['【查无释义】']
		if not result:
			return ['【查无释义】']
		return result

	def randomWords(self, count = config.bubbles.randomWords.count):
		r = rand()
		s = set()
		while len(s) < count:
			result = r.get_random_words(hasDictionaryDef=True, minDictionaryCount=15)
			if result:
				s |= set(result)
		d = {}
		for word in list(s)[:count]:
			d[word] = []

		for key in d:
			d[key] = self.searchWord(key)
		return d

	def makeMsg(self, d, offset = 0):
		chain = MsgChain()
		i = 1 + offset
		for key, val in d.items():
			chain.addPlain(f'{i}. {key}\n')
			i += 1
			for line in val:
				chain.addPlain(f'\t{line}\n')
		return chain

	def run(self, gum, msg):
		if not msg['type'] in ['FriendMessage', 'GroupMessage'] \
				or len(msg['messageChain']) <= 1 \
				or msg['messageChain'][1]['type'] != 'Plain' \
				or msg['messageChain'][1]['text'].split()[0] != '*随机单词':
			return
		splitted = msg['messageChain'][1]['text'].split()
		count = config.bubbles.dailyWordsCount
		if len(splitted) > 1 and splitted[1].isdigit():
			count = int(splitted[1])
		count = max(count, 1)
		count = min(count, 15)

		d = self.randomWords(count)
		chain = self.makeMsg(d)

		if msg['type'] == 'FriendMessage':
			sendFriends(chain, msg['sender']['id'])
		elif msg['type'] == 'GroupMessage':
			sendGroups(chain, msg['sender']['group']['id'])